import SparkMD5 from "spark-md5";
import { ref } from "vue";

/**
 * 计算文件哈希值
 * @returns 哈希计算进度, 计算函数
 */
export function useFileHash() {
    const hashProgress = ref(0);

    /**
     * 文件哈希计算函数
     * @param file 文件对象
     * @param chunkSize 分块大小，默认2MB
     * @returns 哈希值
     */
    const calculate = (file: File, chunkSize = 2 * 1024 * 1024): Promise<string> => {
        return new Promise((resolve, reject) => {
            const chunks = Math.ceil(file.size / chunkSize);
            const spark = new SparkMD5.ArrayBuffer();
            const reader = new FileReader();
            let currentChunk = 0;

            reader.onload = e => {
                if (!e.target?.result) return;
                spark.append(e.target.result as ArrayBuffer);
                currentChunk++;
                hashProgress.value = Math.floor((currentChunk / chunks) * 100);
                // currentChunk < chunks ? loadNext() : resolve(spark.end());
                if (currentChunk < chunks) {
                    loadNext();
                } else {
                    resolve(spark.end());
                }
            };

            reader.onerror = () => reject(new Error("文件读取失败"));

            const loadNext = () => {
                const start = currentChunk * chunkSize;
                const end = Math.min(start + chunkSize, file.size);
                reader.readAsArrayBuffer(file.slice(start, end));
            };

            loadNext();
        });
    };

    return {
        hashProgress,
        calculateFileHash: calculate
    };
}
